/********************************************************************
	created:	2012/02/26   23:22
	filename: 	hy_pool.h
	author:		supercaco@sina.com
	purpose:	
*********************************************************************/
#ifndef _HY_POOL_H_
#define _HY_POOL_H_

#include <deque>
#include <map>
#include "hy_header.h"
#include "hy_mutex.h"
#include "hy_scope_locker.h"
#include "hy_net_base.h"


template<typename Tobj>
class hy_pool_base
{
public:
	hy_pool_base()
	{
		
	}

	virtual ~hy_pool_base()
	{
		clear();
	}

	void push(Tobj* obj)
	{
		hy_assert(obj != NULL);

		_free.push_back(obj);
	}

	void pop(Tobj*& obj)
	{
		if (!_free.empty())
		{
			obj = _free.front();

			_free.pop_front();

			hy_assert(obj != NULL);
		}
	}

	//delete all object in pool
	void clear()
	{
		while (!_free.empty())
		{
			Tobj* obj = _free.front();
			_free.pop_front();
			delete obj;
		}
	}

private:
	typedef std::deque<Tobj*> pool_t;

	pool_t				_free;
};


//*************************************************************
// Class:    hy_pool_with_id<Tobj, Tid>
// Returns:   
// Qualifier: 
//*************************************************************
template<typename Tobj, typename Tid>
class hy_pool_with_id
{
public:
	//*************************************************************
	// Method:    hy_pool_with_id<Tobj, Tid>::hy_pool_with_id
	// Returns:   
	// Qualifier: 
	//*************************************************************
	hy_pool_with_id()
		:_sid(0)

	{
	}
	~hy_pool_with_id(){}

	void push(Tobj* obj,hy_u32_t id)
	{
		_free.push_back(obj);
	}

	void pop(Tobj*& obj, Tid& id)
	{
		id = ++_sid;
		if (!_free.empty())
		{
			obj = _free.front();
			_free.pop_front();
		}
		else
		{
			obj = new Tobj();
		}
	}

	//delete all object in pool
	void clear()
	{
		while (!_free.empty())
		{
			Tobj* obj = _free.front();
			_free.pop_front();
			delete obj;
		}
	}

private:
	typedef std::deque<Tobj*> pool_t;
	
	Tid					_sid;
	pool_t				_free;
};


#endif  //_HY_POOL_H_
